package com.samsung.spen.sshare.networking.connection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.samsung.spen.sshare.R;
import com.samsung.spen.sshare.networking.networkservice.SendReceiveService;
import com.samsung.spen.sshare.networking.networkservice.SendingDataTask;
import com.samsung.spen.sshare.networking.sendreceivefile.SendReceiveActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ConnectionListActivity extends Activity {

	// Mr.DoHai
	public static final String IP = SendReceiveService.IP;
	public static final String PORT = SendReceiveService.PORT;

	public static final int MSG_ADD_ITEM = 1;
	public static final int MSG_DELETE_ITEM = 2;

	private EditText mServerAddr;
	private EditText mTxtServerPort;

	private static ArrayList<NetworkAddress> listItem;
	private static RequestListAdapter adapter;

	private boolean mIsBound;

	private static final String TAG = "CONNECTIONLISTACTIVITY";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.network_connection_list_activity_layout);

		doBindService();

		mServerAddr = (EditText) findViewById(R.id.txtServerAddr);
		mServerAddr.setText("192.168.49.10");
		mTxtServerPort = (EditText) findViewById(R.id.txtServerPort);

		((Button) findViewById(R.id.btnConnect))
				.setOnClickListener(buttonHandler);
		((Button) findViewById(R.id.btnListen))
				.setOnClickListener(buttonHandler);

		/* ArrayList<NetworkAddress> */listItem = new ArrayList<NetworkAddress>();
		/* ArrayAdapter<NetworkAddress> */adapter = new RequestListAdapter(
				this, R.layout.network_connection_row, listItem);

		ListView list = (ListView) findViewById(R.id.listView);
		list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				// NetworkAddress item = adapter.getItem(position);
				// adapter.remove(item);
				//
				// Intent i = new Intent(ConnectionListActivity.this,
				// SendReceiveActivity.class);
				// i.putExtra(IP, item.getmIp());
				// i.putExtra(PORT, "" + item.getMport());
				// startActivity(i);
				showConfirmSendFileDialog(ConnectionListActivity.this, position);
			}
		});
		list.setAdapter(adapter);

	}

	public static Handler uiHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.d(TAG, "MESSAGE TYPE: " + msg.what);
			switch (msg.what) {
			case MSG_ADD_ITEM:
				Log.d(TAG, "MESSAGE TYPE: MSG_ADD_ITEM");
				Bundle receivedData = msg.getData();
				String ipAddr = receivedData.getString("IP");
				int port = receivedData.getInt("PORT");
				for (int i = 0; i < listItem.size(); i++) {
					NetworkAddress item = listItem.get(i);
					if (item.getmIp().equals(ipAddr)) {
						item.setMport(port);
						item.setmStatus(NetworkAddress.CONNECTED);
						adapter.remove(item);
						listItem.add(i, item);
						break;
					}
					if (i == (listItem.size() - 1))
						adapter.add(new NetworkAddress(receivedData
								.getString("IP"), receivedData.getInt("PORT"),
								NetworkAddress.CONNECTED));
				}

				break;
			case MSG_DELETE_ITEM:
				Log.d(TAG, "MESSAGE TYPE: MSG_DELETE_ITEM");
				String ip = msg.getData().getString("IP");
				for (int i = 0; i < listItem.size(); i++) {
					NetworkAddress item = listItem.get(i);
					if (item.getmIp().equals(ip))
						adapter.remove(item);
				}

				break;
			default:
				Log.d(TAG, "MESSAGE TYPE:UNKNOWN --" + msg.what);
				break;
			}

			super.handleMessage(msg);
		}

	};
	OnClickListener buttonHandler = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			// this is clicked when this device 's role is a client
			case R.id.btnConnect:
				String serverIP = mServerAddr.getText().toString();
				int serverPort = Integer.parseInt(mTxtServerPort.getText()
						.toString());
				Map<String, String> addr = new HashMap<String, String>();
				addr.put(SendReceiveService.IP, serverIP);
				addr.put(SendReceiveService.PORT, Integer.toString(serverPort));

				mBoundService.startServer(SendReceiveService.REQUEST_REPLY_SMS,
						addr);
				adapter.add(new NetworkAddress(serverIP, serverPort,
						NetworkAddress.CONNECTED));
				break;
			// this is clicked when user wants to opent a server socket
			case R.id.btnListen:
				NetworkAddress item = new NetworkAddress("192.168.49.1");
				item.setmStatus(NetworkAddress.CONECTING);
				adapter.add(item);
				Log.i(TAG, "vao listen");
				mBoundService.startServer(SendReceiveService.REQUEST_SEND_SMS,
						null);
				Log.i(TAG, "qua start server");
				break;
			default:
				break;
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		doUnbindService();
		finish();
		return super.onMenuItemSelected(featureId, item);
	}

	private SendReceiveService mBoundService;
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Toast.makeText(ConnectionListActivity.this, "Stop service",
					Toast.LENGTH_LONG).show();
			mBoundService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mBoundService = ((SendReceiveService.LocalBinder) service)
					.getService();

		}
	};

	private void doBindService() {
		if (mBoundService == null)
			bindService(new Intent(getApplicationContext(),
					SendReceiveService.class), mConnection,
					Context.BIND_AUTO_CREATE);
		mIsBound = true;
	}

	private void doUnbindService() {
		if (mIsBound) {
			// Detach our existing connection.
			unbindService(mConnection);
			mIsBound = false;
		}
	}

	private void showConfirmSendFileDialog(Context context, final int position) {
		final Dialog dialog = new Dialog(context);
		dialog.setContentView(R.layout.network_confirm_dialog_sendfile);
		dialog.setTitle("Confirm");

		Button btnsendFile = (Button) dialog
				.findViewById(R.id.network_btn_dialog_sendfile);
		Button btnDisconnect = (Button) dialog
				.findViewById(R.id.network_btn_dialog_disconnect);
		Button btnCancel = (Button) dialog
				.findViewById(R.id.network_btn_dialog_cancel);

		btnsendFile.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				NetworkAddress item = adapter.getItem(position);
				Intent i = new Intent(ConnectionListActivity.this,
						SendReceiveActivity.class);
				i.putExtra(IP, item.getmIp());
				i.putExtra(PORT, "" + item.getMport());
				startActivity(i);
				dialog.dismiss();
			}
		});

		btnDisconnect.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				NetworkAddress item = adapter.getItem(position);
				adapter.remove(item);
				(new SendingDataTask()).execute(item.getmIp(), "" + item.getMport(), SendReceiveService.DISCONNECT);
				dialog.dismiss();
			}
		});

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();

	}
}
